package com.bluelight.struts2.examples;

import java.util.logging.Logger;

import com.bluelight.struts2.examples.Service.UserService;
import com.bluelight.struts2.examples.entity.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class LoginAction extends ActionSupport implements ModelDriven<User> {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 2555117861233451400L;
	private User user = new User();
	private UserService userService = new UserService();
	private Logger  logger =Logger.getLogger(getClass().toString());
	public LoginAction() {
	}

	public User getModel() {
		return this.user;
	}

	@Override
	public String execute() throws Exception {
		this.logger.info("This is execute method running!");
		boolean isValid = this.userService.validateUser(this.user);
		if (isValid)
			return SUCCESS;
		else {
			user.setUserName("");
			user.setPassword("");
			return INPUT;
		}
	}

	/**
	 * Use method attribute in action defination like this:
	 * 
	 * <pre>
	 * &lt;action name=&quot;LoginExample&quot;
	 * 			class=&quot;com.bluelight.struts2.examples.LoginAction&quot; method=&quot;login&quot;&gt;
	 * 			&lt;result&gt;/pages/loginResult.jsp&lt;/result&gt;
	 * 			&lt;result name=&quot;input&quot;&gt;/pages/login.jsp&lt;/result&gt;
	 * 		&lt;/action&gt;
	 * </pre>
	 * 
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		logger.info("This is login method running!");
		boolean isValid = this.userService.validateUser(this.user);
		if (isValid)
			return "success";
		else {
			user.setUserName("");
			user.setPassword("");
			return "input";
		}
	}

	private boolean validateUser(User userArg) {
		boolean valid = false;
		if (null != userArg && null != userArg.getUserName()
				&& null != userArg.getPassword()) {
			// TODO User Check
		}

		return valid;
	}

}
